<?php

namespace app\admin\controller;

use classes\RedisClass;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use service\ToolsService;
use think\exception\HttpResponseException;
use think\facade\Cache;

/**
 * 中奖管理
 */
class Lottery extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $lottery = 'tp_lottery_record';
//    public $cate = 'tp_card_cate';


    /**
     * 订单列表
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $this->title = '中奖管理';
        $db = Db::name($this->lottery);
        $get = $this->request->get();

        // =============== 主订单过滤 ===============
        foreach (['sn', 'islottery', 'wecha_id', 'typeid', 'sendstutas', 'prize'] as $field) {
            (isset($get[$field]) && $get[$field] !== '') && $db->whereLike($field, "%{$get[$field]}%");
        }

        // 订单时间过滤
        foreach (['time', 'sendtime'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                list($start, $end) = explode(' - ', $get[$field]);
                $db->whereTime($field, ["{$start} 00:00:00", "{$end} 23:59:59"]);
            }
        }

        //汇总数据
        $lottery_total = Db::name($this->lottery)
            ->where('typeid', 1)
            ->count();
        $reg_total = Db::name($this->lottery)
            ->where('typeid', 2)
            ->count();
        $first = Db::name($this->lottery)
            ->where(['typeid' => 1])
            ->where(['prize' => 1])
            ->count();
        $second = Db::name($this->lottery)
            ->where(['typeid' => 1])
            ->where(['prize' => 2])
            ->count();
        $third = Db::name($this->lottery)
            ->where(['typeid' => 1])
            ->where(['prize' => 3])
            ->count();
        $four = Db::name($this->lottery)
            ->where(['typeid' => 1])
            ->where(['prize' => 4])
            ->count();
        $redpacket = Db::name($this->lottery)
            ->where(['prize' => 3])
            ->sum('remark');

        $this->assign([
            'lottery_total' => $lottery_total,//抽奖总次数
            'reg_total' => $reg_total,//报名总次数
            'first' => $first,
            'second' => $second,
            'third' => $third,
            'four' => $four,
            'redpacket' => $redpacket,
        ]);

        return parent::_list($db->order('id desc'));
    }


    //导出数据
    public function outItems()
    {
        $get = input();

        $db = Db::name($this->lottery)
            ->alias('a')
//            ->join($this->cate . ' b', 'b.cate_id=a.cate_id', 'left')
            ->field('a.id,a.wecha_id,a.typeid,a.islottery,a.name,a.phone,a.address,a.sn,a.prize,a.note,a.time,a.sendstutas,a.sendtime');
//            ->where(['a.is_deleted' => '0']);

        foreach (['sn', 'islottery', 'wecha_id', 'typeid', 'sendstutas'] as $field) {
            (isset($get[$field]) && $get[$field] !== '') && $db->whereLike('a.' . $field, "%{$get[$field]}%");
        }

        // 订单时间过滤
        foreach (['time', 'sendtime'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                list($start, $end) = explode(' - ', $get[$field]);
                $db->whereTime($field, ["{$start} 00:00:00", "{$end} 23:59:59"]);
            }
        }

        $title = '奖励';

        $db->where([]);
        $db->order('a.id desc');
        $data = $db->select();

        $lottery = array(
            '0' => '否',
            '1' => '是',
        );

        $type = array(
            '1' => '中奖',
            '2' => '报名',
        );

        $verify = array(
            '0' => '未核销',
            '1' => '已核销',
        );

        $prize = array(
            '0' => '-',
            '1' => '一等奖',
            '2' => '二等奖',
            '3' => '三等奖',
            '4' => '现金券',
        );

        $newData = array();
        foreach ($data as $one) {
            $one['sendstutas'] = $verify[$one['sendstutas']];
            $one['islottery'] = $lottery[$one['islottery']];
            $one['typeid'] = $type[$one['typeid']];
            $one['prize'] = $prize[$one['prize']];
            $one['time'] = date('Y-m-d H:i:s', $one['time']);
            $one['sendtime'] = $one['sendtime'] > 0 ? date('Y-m-d H:i:s', $one['sendtime']) : '';
            $newData[] = $one;
        }
        $header = array('ID', '用户识别码', '类型', '是否奖励','收货人姓名','收货人手机号','收货人地址', '核销码', '奖项', '奖励名称', '发放时间', '核销状态', '核销时间');
        $name = $title . '数据';
        $result = \classes\Excel::writer($header, $newData, $name, count($header) - 1);

        if ($result) {
            $this->success('导出成功');
        } else {
            $this->error('导出失败');
        }

    }

    /**
     * 订单列表数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _data_filter(&$data)
    {
//        $result = $this->buildOrderList($data);
//        $this->assign([
//            'cates' => ToolsService::arr2table($result['cate'], 'cate_id'),
//        ]);
    }

    public function buildOrderList(&$list)
    {
        $cids = array_unique(array_column($list, 'cate_id'));
        $cateList = Db::name('tp_card_cate')->whereIn('cate_id', $cids)->select();

        foreach ($list as $key => $vo) {
            list($list[$key]['cate']) = [[]];
            foreach ($cateList as $cate) {
                ($vo['cate_id'] === $cate['cate_id']) && $list[$key]['cate'] = $cate;
            }

        }

        $cateField = 'cate_id,pid,name';
//        $cateWhere = ['is_deleted' => '0'];
        $cateWhere = [];
//        $cateList = Db::name($this->cate)->where($cateWhere)->order('sort asc,cate_id asc')->column($cateField);
        return ['list' => $list, 'cate' => $cateList];
    }

    /**
     * 核销
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function verify()
    {

        if (DataService::update($this->lottery)) {
            $id = $this->request->post('id');
            $record = Db::name('tp_lottery_record')->where('id', $id)->find();

            Db::name('tp_lottery_record')
                ->where(['id' => $id])
                ->update([
                    'sendstutas' => 1,
                    'sendtime' => time(),
                ]);

            //清理缓存
            Cache::rm('my_reg_prizes_' . $record['wecha_id']); //删除报名卡券缓存
            RedisClass::clear_prizes_cache($record['wecha_id']); //删除中奖缓存
            $this->success("核销成功！", '');
        }
        $this->error("核销失败，请稍候再试！");
    }

}
